package cn.hzc.fortess.system.eventbus;


import cn.hzc.fortess.core.common.SpringContextHolder;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

public class EventExecute {

    private final static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("eventbus-thread-pool").build();

    private final ExecutorService executorService = new ThreadPoolExecutor(5, 64, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(2048), namedThreadFactory,
            new ThreadPoolExecutor.DiscardPolicy());

    private final AsyncEventBus eventBus = new AsyncEventBus(executorService);

    private final static EventExecute logManager = new EventExecute();

    public final static EventExecute me() {
        return logManager;
    }


    private volatile boolean isreg = false;

    public void post(Event event) {

        checkReg();
        try {
            eventBus.post(event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkReg() {

        if (!isreg) {
            synchronized (this) {
                if (!isreg) {
                    eventBus.register(SpringContextHolder.getBean(LogSubscriber.class));
                    eventBus.register(SpringContextHolder.getBean(MailSubscriber.class));
                    isreg = true;
                }
            }
        }
    }


}
